<?php

namespace app\api\controller;


use app\admin\model\Location;
use app\admin\model\Record;
use app\admin\model\Notifylog;
use app\admin\model\Scan;
use app\admin\model\Whitelist;
use app\admin\model\Send;
use app\admin\model\User;
use app\common\controller\Api;
use app\common\model\MoneyLog;

class Notify extends Api
{
    
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function getResult()
    {
        error_reporting(0);
        $data = file_get_contents("php://input");
        $jsondecode = null;
        if($data) {
            Notifylog::insert(['detail' => $data,'time' => time()]);
            $jsondecode = json_decode($data,true);
            $license = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['license'];
            Scan::insert(['create_time' => time(),'num' => $license]);
            echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
        }
       
        $orderId = $_GET['type'];
        if($orderId) {
            $detail = Record::where(['order_id' => $orderId])->find();
            if($detail['status'] == 3 && $detail['type'] == 1) {//补单且已完成，开闸
                echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
            }
        }
        $openDoor = $_GET['type'];
        if($openDoor == 'openDoor') {
            echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
        }
      
      
        if($jsondecode == null){
            return;
        }
        //白名单的表
        $whiteList = Whitelist::field('num')->select();
        $whiteListNums = array_column(collection($whiteList)->toArray(),'num');
        $license = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['license'];
        Scan::insert(['create_time' => time(),'num' => $license]);
        if(in_array( $license ,$whiteListNums)) {
            //如果是在白名单里,直接开闸。不做其他处理
            echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
        }
        //如果不在白名单里面，检查是不是在当前的付费用户中,这里要区分是进还是出
        $record = Record::where(['num' => $license])->find();
     
        if(empty($record)) {//如果没有付费记录，则不开闸
            return;
        }
        if( !in_array($record['status'],[1,2]) ) {
            return;//如果不是1或者2，没支付，也没有在使用，直接退出
        }
        $moreMoney = Location::find($record->location_id);
        //有付费记录，看看是进还是出
        if($record['status'] == 2) {//出
            $record->end_time = time();
            $record->status = 3; //结束
            $moreMoney ->status = 0;

        } else  {//进
            $moreMoney ->status = 1;
           
            $record->begin_time = time();
            $record->status = 2;//使用中
        }
        $moreMoney ->save();//修改车位状态
        $record->save();
        if($record['status'] == 1) {//如果是进去的，直接放行
            echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
        }
        //计算是否超时
         $sendRecord = Send::where(['location_id' =>  $record['location_id'],'date' => date('Y-m-d')])->find();
       
         $outOfTime = Record::outOfTime( $sendRecord['end_time'], $record->end_time);
        if($outOfTime['type'] == 2) {//5分钟以内。不做任何处理
            echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
        }
     
        $timeOutMoney = $moreMoney['deposit'] * $outOfTime['money'];
        if($outOfTime['type'] == 0) {//如果没有超时或者提前走
            MoneyLog::addMoney($record['user_id'],$timeOutMoney ,'停车提前离场');
            MoneyLog::addMoney($sendRecord['user_id'], $record->money -  $timeOutMoney,'停车费用');
            echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';exit;
        }
        //计算超时费用，生成新的订单
        $insertData = [
            'user_id' => $record['user_id'],
            'location_id' => $record['location_id'],
            'begin_time' => $sendRecord['end_time'],
            'end_time' => time(),
            'num' =>  $record['num'],
            'money' =>  $timeOutMoney,
            'status' => 0,
            'type' => 1,
            'order_id' => Record::generateOrderSn(),
            'master_id' => $record['master_id'],
            'location' => $record['location'],

        ];
        Record::insert($insertData);//重新生成新的订单
        return;
        // $record->more_money = $timeOutMoney;//这里怎么支付是个问题
        // $record->save(); 



        // if(isset($jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFragmentFile']))
        //     {
        //     $small_image = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFragmentFile'];
        //     if( $small_image != null){
        //         $fs_image = fopen("smallimage.jpg", "w");
        //         if(!$fs_image){
        //             return;
        //         }
        //         $simage_decoded = base64_decode($small_image);
        //         $flag2=fwrite($fs_image, $simage_decoded); 
        //         fclose($fs_image);
        //     }
        // }
        // // 大图片
        // if(isset($jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFile']))
        // {
        //     $image = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFile'];
        //     if( $image != null){
        //         $fp_image = fopen("image.jpg", "w");
        //         if(!$fp_image){
        //             return;
        //         }
        //         $image_decoded = base64_decode($image);
        //         $flag=fwrite($fp_image, $image_decoded); 
        //         fclose($fp_image);
        //     }
        // }
        
      
        // $fp_license  = fopen("license.txt", "w");
        // if($fp_license  )
        // { 
        //     $flag=fwrite($fp_license  , $license ); 
        //     fclose($fp_license);
        // }
        // 发送开闸命令
       
        
    }
    public function getFastResult()
    {
        error_reporting(0);
        // $whiteList = Whitelist::field('num')->select();
        // $whiteListNums = array_column(collection($whiteList)->toArray(),'num');
         
        $data = file_get_contents("php://input");
       
        error_log( $data,3,'log2.log');
        $data1 = $_GET;
        $data2 = $_POST;
      
        error_log('get'.json_encode($data1)."\r\n",3,'log2.log'); 
        error_log('post'.json_encode($data2)."\r\n",3,'log2.log'); 
        echo '1234';die;
        $fp = fopen("snap_shot.txt", "w");
        if(!$fp){
            return;
        }
        $flag=fwrite($fp, $data); 
        //$flag=fwrite($fp, $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imagePath']); 
        if(!$flag) 
        { 
            fclose($fp);
            return;
        } 
        fclose($fp);
        $jsondecode = json_decode($data,true);

        if($jsondecode == null){
            return;
        }
        if(isset($jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFragmentFile']))
            {
            $small_image = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFragmentFile'];
            if( $small_image != null){
                $fs_image = fopen("smallimage.jpg", "w");
                if(!$fs_image){
                    return;
                }
                $simage_decoded = base64_decode($small_image);
                $flag2=fwrite($fs_image, $simage_decoded); 
                fclose($fs_image);
            }
        }
        // 大图片
        if(isset($jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFile']))
        {
            $image = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imageFile'];
            if( $image != null){
                $fp_image = fopen("image.jpg", "w");
                if(!$fp_image){
                    return;
                }
                $image_decoded = base64_decode($image);
                $flag=fwrite($fp_image, $image_decoded); 
                fclose($fp_image);
            }
        }
        $license = $jsondecode['AlarmInfoPlate']['result']['PlateResult']['license'];
        $fp_license  = fopen("license.txt", "w");
        if($fp_license  )
        { 
            $flag=fwrite($fp_license  , $license ); 
            fclose($fp_license);
        }
        // 发送开闸命令
        echo '{"Response_AlarmInfoPlate":{"info":"ok","content":"...","is_pay":"true"}}';
        
    }
    public function heartBeat()
    {
        error_reporting(0);
        // $whiteList = Whitelist::field('num')->select();
        // $whiteListNums = array_column(collection($whiteList)->toArray(),'num');
         
        $data = file_get_contents("php://input");
        $data1 = $_GET;
        $data2 = $_POST;
        error_log($data."\r\n",3,'heart.log'); 
        error_log('get'.json_encode($data1)."\r\n",3,'heart.log'); 
        error_log('post'.json_encode($data2)."\r\n",3,'heart.log'); 
        // $fp = fopen("heart.txt", "w");
        // if(!$fp){
        //     return;
        // }
        // $flag=fwrite($fp, $data); 
        // //$flag=fwrite($fp, $jsondecode['AlarmInfoPlate']['result']['PlateResult']['imagePath']); 
        // if(!$flag) 
        // { 
        //     fclose($fp);
        //     return;
        // } 
        // fclose($fp);
    }
}
